var Util = require('../../utils/util.js');
const Api = require('../../api/api.js')
var app = getApp()

Page({
  data: {
    hasEmptyGrid: false,
    hasLastEmptyGrid: false,
    cur_year: '',
    cur_month: '',
    calendarMap: [
      {
        date: '2017-10-1',
        price: '180',
        ticket: '1000'
      },
      {
        date: '2017-10-2',
        price: '180',
        ticket: '无限库存'
      }
    ],
    days: [],
    curDate: null,
    selectedNote: 0,
    ticketId: ''

  },
  onLoad(paras) {
    let that = this;
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];

    this.setData({
      ticketId: paras.ticketId,
      cur_year: cur_year,
      cur_month: cur_month,
      weeks_ch
    })

    this.getDayPrice();
    console.log(this.data.days)
  },
  // 获取一个月天数
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },
  // 获取每个月第一天的日期
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  // 获取每个月最后一天日期
  getLastDayOfWeek(year, month) {
    let lastDay = this.getThisMonthDays(year, month);
    console.log('lastDay' + lastDay)
    return new Date(Date.UTC(year, month - 1, lastDay)).getDay();
  },
  // 处理占位模块
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    const lastDayOfWeek = this.getLastDayOfWeek(year, month)
    console.log(lastDayOfWeek)
    let empytGrids = [];
    let lastEmptyGrids = []
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
    if (lastDayOfWeek < 5) {
      for (let i = lastDayOfWeek; i < 6; i++) {
        lastEmptyGrids.push(i);
      }
      this.setData({
        hasLastEmptyGrid: true,
        lastEmptyGrids
      });
    } else {
      this.setData({
        hasLastEmptyGrid: false,
        lastEmptyGrids: []
      });
    }
  },
  // 设置日期
  calculateDays(year, month) {
    let _days = [], that = this;
    const thisMonthDays = this.getThisMonthDays(year, month);
    for (let i = 1; i <= thisMonthDays; i++) {
      let _day = that.compareDate(i)
      _days.push(_day);
    }
    this.setData({
      days: _days
    });
  },
  // 切换月份
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    if (handle === 'prev') {
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }

      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);

    } else {
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }

      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
    }
  },
  // 对比日期
  compareDate: function (day) {
    let str = this.data.cur_year + '-' + this.changeDateType(this.data.cur_month) + '-' + this.changeDateType(day),
      newDay = {
        day: day,
        hasData: false
      };
    this.data.calendarMap.map((item, index) => {
      if (item.date === str) {
        newDay = {
          day: day,
          index: index,
          price: item.price,
          hasData: true
        }
      }
    })
    return newDay;
  },
  // 改一下日历的格式
  changeDateType: function (str) {
    let newStr = '0' + str;
    return newStr.substr(newStr.length - 2, 2)
  },
  // 选择日历
  selectDay: function (e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      curDate: this.data.calendarMap[index],
      selectedNote: index
    })
  },
  //获取日期库存
  getDayPrice: function () {
    var pagethis = this
    Api.getDayPrice({
      data: app.addParams({
        ticketId: pagethis.data.ticketId
      }),
      success: (res) => {
        console.log('+++++++++++++++获取日历数据+++++++++++++++')
        console.log(res)
        if (res.data.data.length > 0) {
          pagethis.setData({
            calendarMap: res.data.data,
            curDate: res.data.data[0],
          })
          pagethis.calculateEmptyGrids(pagethis.data.cur_year, pagethis.data.cur_month);
          pagethis.calculateDays(pagethis.data.cur_year, pagethis.data.cur_month);
        }

      },
      fail: (res) => {
        wx.showModal({
          showCancel: false,
          title: '出错啦',
          content: `${error.msg} `
        })
      }
    })
  },
  // 完成选择
  hasSelected: function () {
    let that = this;
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];  //上一个页面

    let tprice = Util.getTotalPrice(prevPage.data.num.value, that.data.curDate.price);
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    prevPage.setData({
      totalprice: tprice,
      price: that.data.curDate.price,
      bookday: that.data.curDate.date
    })
    wx.navigateBack()
  },
  // 放弃选择
  giveUp:function(){
    wx.navigateBack()
  },
  onShareAppMessage() {
    return {
      title: '小程序日历',
      desc: '还是新鲜的日历哟',
      path: 'pages/index/index'
    }
  }
})

